package com.mars.basic.service;

import com.mars.basic.allmain.po.*;
import com.mars.basic.allmain.vo.RolePermissionVo;
import com.mars.basic.repository.RolePermissionRepository;
import com.mars.common.utils.DslUtils;
import com.querydsl.core.Tuple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RolePermissionService {
    @Autowired(required = false)
    private RolePermissionRepository repository;

    public RolePermissionRepository getRepository() {
        return repository;
    }

    public boolean check(RolePermissionVo vo){
        boolean exists = getRepository().exists(QRolePermission.rolePermission.permissionId.eq(vo.getPermissionId()).and(QRolePermission.rolePermission.roleId.eq(vo.getRoleId())));
        return !exists;
    }

    public List<Role> findRolesByUrl(String url) {
        List<Tuple> fetch = DslUtils.getJPAQueryFactory().select(QRole.role, QRolePermission.rolePermission, QRolePermission.rolePermission)
                .from(QRole.role).on(QRole.role.status.eq("0"))
                .leftJoin(QRolePermission.rolePermission).on(QRolePermission.rolePermission.roleId.eq(QRole.role.id))
                .leftJoin(QPermission.permission).on(QPermission.permission.id.eq(QRolePermission.rolePermission.permissionId))
                .where(QPermission.permission.url.eq(url).and(QPermission.permission.status.eq("0"))).fetch();
        List<Role> roles = fetch.stream().map(o -> o.get(QRole.role)).collect(Collectors.toList());
        return roles;
    }
}
